package com.rhok.wthru_client.servermsgs;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.List;
import java.util.Vector;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;

import android.content.Context;
import android.util.Log;

import com.rhok.wthru_client.GlobalConfiguration;

/**
 * 
 * Base class for subscribing REST messages to the web server.
 * Any type of message should extend this class with the required fields 
 *
 * For sending message, please use ServerMessageTask
 * @see ServerMessageTask
 */
public abstract class ServerMessage {
	
	private static final String LOG_TOPIC = "WTHRU_ServerMessage";

	protected Context m_context;
	protected List<NameValuePair> m_requestValues;
	private String m_serverUrl;

	// XXX: Currently supporting a single server. In the future it should 
	// be modified to support multiple servers and either try one-by-one or
	// a few in parallel
	
	private void selectServer() {
		GlobalConfiguration conf = GlobalConfiguration.getInstance(m_context);
		m_serverUrl = conf.getString("servers");
	}
	
	protected abstract String getRequestPath();
	public abstract String send();
	
	protected void addStandardRequestHeaders() {
		
	}

	public ServerMessage(Context context) {
		m_context = context;
		m_requestValues = new Vector<NameValuePair>();
		selectServer();
	}
	
	public String sendPostWithResponse() {
		HttpResponse response = sendPostRequest();
		return getResponseString(response);
	}

	public HttpResponse sendPostRequest() {
		String serverUrl = m_serverUrl + "/" + getRequestPath();
		
		HttpClient httpClient = new DefaultHttpClient();
		HttpPost httpPost = new HttpPost(serverUrl);

		addStandardRequestHeaders();
		try {
			httpPost.setEntity(new UrlEncodedFormEntity(m_requestValues));
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		Log.d(LOG_TOPIC, "Full URL: " + httpPost.getURI().toString());
		
		// Execute HTTP Post Request
		HttpResponse response = null;
		try {
			Log.i(LOG_TOPIC, "Attempting to send message of type '" + this.getClass().getName() + "' to " + serverUrl + "...");
			response = httpClient.execute(httpPost);
			
			return response;
		} catch (ClientProtocolException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return null;
		
	}

	// Utility function for fetching the response body from HttpResponse object
	protected static String getResponseString(HttpResponse response) {
		String result = "";
		try {
			InputStream in = response.getEntity().getContent();
			BufferedReader reader = new BufferedReader(new InputStreamReader(in));
			StringBuilder str = new StringBuilder();
			String line = null;
			while((line = reader.readLine()) != null){
				str.append(line + "\n");
			}
			in.close();
			result = str.toString();
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		return result;
	}
	
}
